import Vue from 'vue'
import VueRouter from 'vue-router'
import {routers, otherRouter, menuRouter} from './router'
import iView from 'iview'
import {isEmptyObject} from "../common/vue-expand-func";
import {checkAccess} from "./permission";
import {profile} from "../config/base";

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  routes: routers
})


/**
 * 路由跳转前
 */
router.beforeEach((to, from, next) => {
  if (to.meta.title)
    document.title = to.meta.title

  /** 权限校验 **/
  if (!profile.isDev && !checkAccess(to.meta.access)) {
    router.replace({name: 'error_404'})
    return
  }

  iView.LoadingBar.start()
  router.app.$options.store.dispatch('pageChange', true)

  if (to.meta.notNeedToken) {
    /** 不需要token进入的页面 **/
    if (to.name === 'login' && checkHasLogin(router)) {
      next({
        name: 'home_index'
      })
    } else {

      next()
    }
  } else {
    if (!checkHasLogin(router)) {
      next({
        name: 'login'
      })
    } else {
      /** 检测是否存在该路由 **/
      toDefaultPage(to, next)
    }
  }
})

function checkHasLogin(router) {
  if (profile.isDev)
    return true
  return !isEmptyObject(router.app.$options.store.state.userInfo.token);
}

function toDefaultPage(to, next) {
  let routerArr = [otherRouter, ...menuRouter]

  let parentRouter = {}
  let targetName = to.name === 'otherRouter' ? 'home' : to.name
  routerArr.map(item => {
    if (item.name === targetName) {
      parentRouter = item
    }
  })
  if (!isEmptyObject(parentRouter)) {
    /** 符合一级路由的name就跳到二级路由的第一个 **/
    router.replace({
      name: parentRouter.children[0].name
    });
  } else {
    next()
  }
}

/**
 * 跳转后
 */
router.afterEach(() => {
  iView.LoadingBar.finish()
  router.app.$options.store.dispatch('pageChange', false)
})

export default router
